package com.aier.user.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aier.admin_new.common.AndroidTag;
import com.aier.admin_new.common.AndroidType;
import com.aier.admin_new.common.CompresszZipFile;
import com.aier.admin_new.common.MessageBaiduYunSendTransmitter;
import com.aier.classes.common.InviteRequestUtil;
import com.aier.classes.entity.ClassStudent;
import com.aier.classes.entity.ClassTeacher;
import com.aier.classes.entity.Classes;
import com.aier.classes.entity.Homework;
import com.aier.classes.entity.HomeworkCR;
import com.aier.classes.entity.HomeworkComment;
import com.aier.classes.service.IClassService;
import com.aier.classes.service.IClassUserService;
import com.aier.common.common.CommonSession;
import com.aier.common.common.Constant;
import com.aier.common.common.ICommonDAO;
import com.aier.common.common.ImageUtil;
import com.aier.common.common.SendSchoolPhoneMessage;
import com.aier.common.common.SystemConfigStatic;
import com.aier.common.service.ISysPhoneMessageService;
import com.aier.school.entity.School;
import com.aier.user.entity.User;
import com.aier.user.service.IHsConBookService;
import com.aier.user.service.IUserBuyService;
import com.aier.user.service.IUserService;
import com.baidu.yun.channel.model.BindInfo;

@Scope("prototype")
@Component("userHomeworkAction")
public class UserHomeworkAction extends UserBaseAction {

    /**
     * 作业
     */
    private static final long serialVersionUID = 1L;
    
    @Resource(name = "userService")
    private IUserService userService;
    @Resource(name = "hsConBookService")
    private IHsConBookService hsConBookService;
    @Resource(name = "classUserService")
    private IClassUserService classUserService;
    @Resource(name = "classService")
    private IClassService classService;
    @Resource(name = "sysPhoneMessageService")
    private ISysPhoneMessageService sysPhoneMessageService;
    @Resource(name = "userBuyService")
    private IUserBuyService userBuyService;

    private int s; // 错误码
    private int page; // 页数
    private int page_size; // 每页的记录数
    private int page_count; // 总页数
    private int count; // 总数

    private List<Homework> hwList; // 作业列表
    private HomeworkCR hcr; // 作业评论的某条回复

    private Long cid; // 班级id
    private Long tid; // 教师id
    private Long hid; // 作业id
    private Long chid; // 评论id
    private Short type; // 身份类型（1教师2家长）
    private File file; // 图片
    private String title;   // 作业标题
    private String content; // 作业内容
    private String imageName; // 图片名称
    private Boolean isSendPhone = false; // 是否发送短信

    private String photoName; // 上传图片的名称或路径
    
    private Integer mesCount; // 学校剩余短信数量
    
    private Integer peoCount; // 作业短信发送的人数
    private Homework homework;
    private String unreadingList;  // 作业未读列表
    private List<ClassStudent> readingList; // 作业已读列表
    private HomeworkComment hc; // 作业评论
    private Long crhid; // 作业评论的回复id
    private Long uid;//回复人的id
    private Long sid;
    
    @Override
    public String execute() {
        mesCount = classService.searchClassById(cid).getMesCount();
        s = 1;
        return SUCCESS;
    }
    
    // 发布作业前提示发送短信条数
    public String searchMessageCount() {
        s = 1;
        List<User> uList = classUserService.searchAllClassParentList(cid);
        
        // 判断作业的长度,计算每条评语需要发送几条短信
        title = InviteRequestUtil.getFilterMessage(title);
        content = InviteRequestUtil.getFilterMessage(content);
        content = title +":"+content;
        Classes cl = classService.searchClassById(cid);
        content = content + "【" + cl.getCname() + "】" + "【爱儿360】";        
        
        int size = 1;
        
        if (content.length() > Constant.num_70) {
            int len = content.length();
            size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
        }
        
        mesCount = uList.size()*size;
        peoCount = uList.size();
        
        School school = userBuyService.searchSchoolMessageCount(cid);
        if (school.getMethod() == 2) {
            int c = classService.searchClassById(cid).getMesCount();
            // 短信条数不足
            if (c < mesCount) {
                s = 0;
            }
        }
        
        return SUCCESS;
    }

    /**
     * 教师发布作业
     * 
     * @return
     */
    public String commitHomework() {
        s = 1;
        List<ClassStudent> ctList = classUserService.searchAllClassStudentList(cid);
        Long hid = hsConBookService.insertHomework(cid, tid,title, content, imageName,ctList.size());
        // 是否发送短信
        if (isSendPhone) {
            List<List<String>> userPhoneList = new ArrayList<List<String>>();

            List<User> uList = classUserService.searchAllClassParentList(cid);
            for (User u : uList) {
                List<String> list = new ArrayList<String>();
                list.add(u.getPhone());
                list.add(u.getUid().toString());
                list.add("0");
                userPhoneList.add(list);
            }
            if (userPhoneList.size() > 0) {
                
                Classes cl = classService.searchClassById(cid);
                
                // 判断作业的长度,计算每条作业需要发送几条短信
                title = InviteRequestUtil.getFilterMessage(title);
                content = InviteRequestUtil.getFilterMessage(content);
                content = title +":"+content;
                content = content + "【" + cl.getCname() + "】" + "【爱儿360】";
                
                int size = 1;
                
                if (content.length() + Constant.num_7 > Constant.num_70) {
                    int len = content.length()+Constant.num_7;
                    size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
                }
                
                new SendSchoolPhoneMessage(userPhoneList, content, cl.getSid(),
                        sysPhoneMessageService,Constant.num_3,hid,size,tid).start();
                
            }
            
        }
        mesCount = classService.searchClassById(cid).getMesCount();
        return SUCCESS;
    }
    
    /**
     * 获取作业列表
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String searchHomework() {
        if (page <= 0) {
            page = 1;
        }
        if (page_size <= 0) {
            page_size = Constant.num_10;
        }
        Map<String, Object> map = hsConBookService.searchHomework(page,
                page_size, cid);

        if (null != map) {
            page_count = (Integer) map.get(ICommonDAO.PAGE_COUNT);
            count = (Integer) map.get(ICommonDAO.COUNT);
            page = (Integer) map.get(ICommonDAO.PAGE);
            hwList = (List<Homework>) map.get(ICommonDAO.OBJ_LIST);
        }
        s = 1;
        return SUCCESS;
    }
    
    /**
     * 获取作业详情
     * 
     * @return
     */
    public String searchHomeworkDetail() {
        // 修改阅读量（家长）
        if (type == 2) {
            hsConBookService.insertHomeworkReading(hid,uid);
        }
        
        homework = hsConBookService.searchHomework(hid);
        homework.setHcList(hsConBookService.searchHCList(hid));
        for (int i = 0; i < homework.getHcList().size(); i++) {
            homework.getHcList().get(i).setHcrList(hsConBookService.searchHCRList(homework.getHcList().get(i).getChid()));
        }
        // 已阅和未阅列表
        unreadingList = hsConBookService.searchUnReadingList(hid);
        readingList = hsConBookService.searchCSByCondition(hid);
        s = 1;
        return SUCCESS;
    }

    /**
     * 评论作业或晒作业
     * @return
     */
    public String commentHomework() {
        hc = hsConBookService.insertHComment((Long) request.getSession().getAttribute(CommonSession.SESSION_ACCOUNT_ID), hid, content,imageName, type, tid);
        s = 1;
        return SUCCESS;
    }

    /**
     * 回复评论
     * 
     * @return
     */
    public String replyComment() {
        hcr = hsConBookService.insertReply((Long) request.getSession().getAttribute(CommonSession.SESSION_ACCOUNT_ID), chid, content,
                type, tid);
        s = 1;
        return SUCCESS;
    }
    
    /**
     * 删除作业评论
     * @return
     */
    public String deleteComment() {
        s = hsConBookService.deleteComment(chid);
        return SUCCESS;
    }
    
    /**
     * 删除作业评论的回复
     * @return
     */
    public String deleteReply() {
        s = hsConBookService.deleteReply(crhid);
        return SUCCESS;
    }
    
    /**
     * 客户端教师发布作业
     * 
     * @return
     */
    public String commitHomeworkApp() {
        s = 1;
        String picName="";
    	if(file!=null && (photoName!=null |  photoName.equals("")==false)){
    		picName = CompresszZipFile.uploadDailyfoodImgApp(file, photoName,SystemConfigStatic.homework_upload_url);
    	}
       
        List<ClassStudent> ctList = classUserService.searchAllClassStudentList(cid);
        Long hid = hsConBookService.insertHomework(cid, tid,title, content, picName,ctList.size());
        // 是否发送短信
        if (isSendPhone) {
            List<List<String>> userPhoneList = new ArrayList<List<String>>();

            List<User> uList = classUserService.searchAllClassParentList(cid);
            for (User u : uList) {
                List<String> list = new ArrayList<String>();
                list.add(u.getPhone());
                list.add(u.getUid().toString());
                list.add("0");
                userPhoneList.add(list);
            }
            if (userPhoneList.size() > 0) {
                
                Classes cl = classService.searchClassById(cid);
                
                // 判断作业的长度,计算每条作业需要发送几条短信
                title = InviteRequestUtil.getFilterMessage(title);
                content = InviteRequestUtil.getFilterMessage(content);
                content = title +":"+content;
                content = content + "【" + cl.getCname() + "】" + "【爱儿360】";
                
                int size = 1;
                
                if (content.length() + Constant.num_7 > Constant.num_70) {
                    int len = content.length()+Constant.num_7;
                    size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
                }
                
                new SendSchoolPhoneMessage(userPhoneList, content, cl.getSid(),
                        sysPhoneMessageService,Constant.num_3,hid,size,tid).start();
                
            }
            
        }
        mesCount = classService.searchClassById(cid).getMesCount();
        //推送
        MessageBaiduYunSendTransmitter mbysst = new MessageBaiduYunSendTransmitter(AndroidTag.CLASS+sid+cid, title,"您有一条新的作业#"+hid, AndroidType.CLASSWORK, uid, 1);
        mbysst.sendServer();
        return SUCCESS;
    }

    /**
     * 客户端评论作业或晒作业
     * @return
     */
    public String commentHomeworkApp() {
    	 String picName="";
     	if(file!=null && (photoName!=null |  photoName.equals("")==false)){
     		picName = CompresszZipFile.uploadDailyfoodImgApp(file, photoName,SystemConfigStatic.homework_upload_url);
     	}	
     	
        hc = hsConBookService.insertHComment(uid, hid, content,
                picName, type, tid);
        com.aier.user.entity.User user=userService.getAppUid(uid);
        MessageBaiduYunSendTransmitter mbysst = new MessageBaiduYunSendTransmitter(AndroidTag.CLASS+sid+cid, title,user.getNickname()+"评论的你的作业#"+hid, AndroidType.CLASSWORK, uid, 1);
        mbysst.sendServer();
        s = 1;
        
        return SUCCESS;
    }
    
    /**
     * 客户端回复评论
     * 
     * @return
     */
    public String replyCommentApp() {
    	if(type==null || tid ==null){
    		type=-1;
    		tid=1L;
    	}
        hcr = hsConBookService.insertReply(uid, chid, content,type, tid);
        List<HomeworkComment> list=hsConBookService.searchHCList(chid);
        if(list.size()>0){
        	hc=list.get(0);
	        com.aier.user.entity.User user=userService.getAppUid(hc.getUid());
	        MessageBaiduYunSendTransmitter mbysst = new MessageBaiduYunSendTransmitter(user,"作业有条回复",user.getNickname()+"回复了你#"+chid,AndroidType.CLASSWORKREPLYE,uid,2);
	        mbysst.sendServer();
        }
        s = 1;
        return SUCCESS;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setPage_size(int page_size) {
        this.page_size = page_size;
    }

    public int getS() {
        return s;
    }

    public void setHsConBookService(IHsConBookService hsConBookService) {
        this.hsConBookService = hsConBookService;
    }

    public void setCid(Long cid) {
        this.cid = cid;
    }

    public void setSid(Long sid) {
		this.sid = sid;
	}

	public void setTid(Long tid) {
        this.tid = tid;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public void setType(Short type) {
        this.type = type;
    }

    public void setClassUserService(IClassUserService classUserService) {
        this.classUserService = classUserService;
    }
    public void setHid(Long hid) {
        this.hid = hid;
    }

    public void setChid(Long chid) {
        this.chid = chid;
    }

    public List<Homework> getHwList() {
        return hwList;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public void setClassService(IClassService classService) {
        this.classService = classService;
    }

    public Long getTid() {
        return tid;
    }

    public Long getCid() {
        return cid;
    }

    public Short getType() {
        return type;
    }

    public int getPage_count() {
        return page_count;
    }

    public int getCount() {
        return count;
    }

    public int getPage() {
        return page;
    }

	public void setSysPhoneMessageService(
            ISysPhoneMessageService sysPhoneMessageService) {
        this.sysPhoneMessageService = sysPhoneMessageService;
    }

    public void setIsSendPhone(Boolean isSendPhone) {
        this.isSendPhone = isSendPhone;
    }

    public void setUserBuyService(IUserBuyService userBuyService) {
        this.userBuyService = userBuyService;
    }

    public HomeworkCR getHcr() {
        return hcr;
    }

    public Integer getMesCount() {
        return mesCount;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getPeoCount() {
        return peoCount;
    }

    public Homework getHomework() {
        return homework;
    }

    public String getUnreadingList() {
        return unreadingList;
    }

    public List<ClassStudent> getReadingList() {
        return readingList;
    }

    public HomeworkComment getHc() {
        return hc;
    }

    public void setCrhid(Long crhid) {
        this.crhid = crhid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

	public void setFile(File file) {
		this.file = file;
	}

	public void setPhotoName(String photoName) {
		this.photoName = photoName;
	}
}
